package common.serializer.mySerializer;

import com.alibaba.fastjson.JSONObject;
import common.Message.RpcRequest;
import common.Message.RpcResponse;

public class JsonSerializer implements Serializer {
    @Override
    public byte[] serialize(Object object) {
        byte[] b = JSONObject.toJSONBytes(object);
        return b;
    }

    @Override
    public Object deserialize(byte[] bytes, int messageType) {
        Object obj;
        switch (messageType) {
            case 0:
                // 将字节数组转化为RpcRequest对象
                RpcRequest request = JSONObject.parseObject(bytes, RpcRequest.class);
                // 创建Object类型数组，存储解析后的请求参数
                Object[] objects = new Object[request.getParamTypes().length];
                // fastJson可以将json数组转化为数组对象，直接赋值给数组对象
                for (int i = 0; i < objects.length; i++) {
                    // paramsType是目标参数类型，request.getParamTypes()[i]是目标参数类型数组中的元素,表示参数目标类型
                    Class<?> paramsType = request.getParamTypes()[i];
                    if (!paramsType.isAssignableFrom(request.getParams()[i].getClass())) {
                        objects[i] = JSONObject.toJavaObject((JSONObject) request.getParams()[i],
                                request.getParamTypes()[i]);
                    } else
                        // 类型兼容直接赋值
                        objects[i] = request.getParams()[i];
                }
                request.setParams(objects);
                obj = request;
                break;
            case 1:
                // 将字节数组转化为RpcResponse对象
                RpcResponse response = JSONObject.parseObject(bytes, RpcResponse.class);
                // 根据对象获取对象类型
                Class<?> dataType = response.getDataType();
                if (dataType != null && !dataType.isAssignableFrom(response.getData().getClass())) {
                    response.setData(JSONObject.toJavaObject((JSONObject) response.getData(), dataType));
                }
                obj = response;
                break;
            default:
                System.out.println("不支持的序列化类型");
                throw new RuntimeException();
        }
        return obj;
    }

    @Override
    public int getType() {
        return 1;
    }
}
